﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using gtasks.Auth;
using gtasks.Model.Convert;
using pub.CmdUI.UI.Control;
using pub.NET20Fix;
using pub.Types;
using todo;
using todo.Model;
using todo.Persistence;
using todo.Plugin;
using todo.Ribbon;
using todo.Ribbon.CmdUI;

namespace gtasks
{
    public class GtasksPlugin : IPlugin
    {
        private RibbonButton _btn;
        private MenuItem _mn;
        private GtasksCmd _cmd;

        public string Name
        {
            get { return "gtasks"; }
        }

        public void Initialize()
        {
            _cmd = new GtasksCmd();
        }

        public void OnRibbonInited(RibbonUI ribbonUi)
        {
            _btn = new RibbonButton(ribbonUi, 3100);
            App.CmdUIManager.Bind(_cmd, new RibbonButtonUI(_btn));
        }

        public void OnSave(string filePath, TodoList todoList)
        {
            var folder = Path.GetDirectoryName(filePath);
            var gtasksFolder = Path.Combine(App.DataPath, "gtasks");
            if (folder != gtasksFolder)
            {
                return;
            }
//            var id = todoList.Id;
//            var synchronizer = new Synchronizer();
//            synchronizer.Sync(filePath, todoList);
            var frm = new SaveTasklistForm();
            frm.FilePath = filePath;
            frm.TodoList = todoList;
            frm.ShowDialog();

            var newIdMap = frm.NewIdMap;
            if (newIdMap.Count > 0)
            {
                var json = fastJSON.JSON.Instance.ToJSON(newIdMap);
                App.MainForm.Www.Document.InvokeScript("todo_setNewIds", new object[] { json });
            }
        }

        public void OnOpen(string fileName)
        {
            var folder = Path.GetDirectoryName(fileName);
            var gtasksFolder = Path.Combine(App.DataPath, "gtasks");
            if (folder != gtasksFolder)
            {
                return;
            }
            var todoList = TodoListParser.Parse(fileName);
            if (string.IsNullOrEmpty(todoList.Id))
            {
                Debug.Print("bad gtasks todolist");
                return;
            }
            //var updateTime = TaskListManager.Instance.GetUpdateTime(todoList.Id);
            var frm = new OpenTasklistForm();
            frm.FileName = fileName;
            frm.TodoList = todoList;
            frm.ShowDialog();

            if (frm.Canceled)
            {
                throw new AbortException();
            }
        }

        public void OnClassicUIInited()
        {
            App.MainForm.MenuTools.MenuItems.Add("-");
            var caption = "Google Tasks";
#if zh
            caption = "Google 任务";
#endif
            _mn = App.MainForm.MenuTools.MenuItems.Add(caption);
            App.CmdUIManager.Bind(_cmd, new MenuUI(_mn));
        }

    }
}